const http = require("http");
const https = require("https");
const caw = require("caw");
const protocolMap = {
	"https:": https,
	"http:": http
};
const url = require("url");
const fs = require("fs");
// https.globalAgent = caw("http://127.0.0.1:8118", {
// 	protocol: "https"
// });

exports.setup = router => {
	router.get("/proxy", async (ctx, next) => {
		const { res } = ctx;
		const { src } = ctx.query;
		const src_info = url.parse(src);
		try {
			if (src === "http://g-cdn.youdob.com/home/Avatar_01.png") {
				throw "use back imag";
			}
			const protocol = protocolMap[src_info.protocol];
			await new Promise((resolve, reject) => {
				protocol.get(src, response => {
					if (response.statusCode === 200) {
						res.writeHead(200, {
							"Content-Type": response.headers["content-type"]
						});
						response.pipe(res);
						response.on("end", resolve);
					} else {
						reject();
					}
				});
			});
		} catch (e) {
			console.log("USE BACK IMAGE");
			res.writeHead(200, {
				"Content-Type": "image/png"
			});
			await new Promise((resolve, reject) => {
				fs
					.createReadStream(
						__dirname + "/../client/resources/home/Avatar_01.png"
					)
					.pipe(res)
					.on("end", resolve);
			});
		}
	});
};
